package com.mustafa.payment;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

class PaymentApplicationTests {

    @Test
    void contextLoads() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String content = "NjM3MTE4YzljNzUwZDA3ZjQ4M2EyMDRkNzc2ZWJmNzk1ZjMzOWM3YTU4YTQwNTM2MjlmNGViODJkYzM0N2NjNXx8YjRhNmFlNGZiNzNhOWMzZDI0MmNlZjQ4MzVhNGEzY2F8fDM0NzA2Y2U5Njc4NmMwNDk5ODc0NTU1MzllZjNlNmFkZjI0ZmRjNmQ2MDk2NGQ0Y2JkMGRjOWVlZWJlYWZmM2VkNzAzMDI1ZmI2YzFhZGE4ZDQ5MmYyYTQzMTBmNWJmNmU3OWI2Yjg5MTQ4OTNmMzlhMWM5ZmU2MzZjMjg4Yjk3ZTRkYjViODg5NjAxYTA4MWE4MjFjNDExYTI3ZDc1NmFhOWVjNDZhYTRjMmU4OWFiZGFkYzdhMjQ4OWVmYzk4ODdmM2I5MzkyOTQ5N2U1MmUzNGNiMzg4MTk0ZjY3ODZmODY4NGNkMWVjM2ExZTU0ZjFlNjkyNjQ2NDEwMjhlNmQ=";

        // 获取Base64解码器
        Base64.Decoder decoder = Base64.getDecoder();

        // 使用解码器对编码的字符串进行解码
        byte[] decodedBytes = decoder.decode(content);

        // 将解码后的字节转换为字符串
        String decodedString = new String(decodedBytes);

        String[] decodedArrary = decodedString.split("\\|\\|");
        String key = decodedArrary[0];
        String iv = decodedArrary[1];
        content = decodedArrary[2];

        byte[] keyBytes = hexStringToByteArray(key);
        byte[] ivBytes = hexStringToByteArray(iv);

        // 将十六进制字符串转换为字节数组
        byte[] encryptedText = hexStringToByteArray(content);

        // 创建 SecretKeySpec 和 IvParameterSpec 对象
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        // 初始化 Cipher 对象
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        // 进行解密
        byte[] decrypted = cipher.doFinal(encryptedText);

        // 打印解密后的结果
        System.out.println(new String(decrypted, StandardCharsets.UTF_8));

    }

    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

}
